package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.AttendanceSummaryStaffDialog;
import com.isunland.managesystem.entity.AttendanceSummaryStaffDialog.SummaryStaff;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.MessageContact;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class SearchPersonListFragment extends BaseListFragment {
  public static final String EXTRA_VALUE = "com.isunland.managesystem.ui.extra_value";
  public static final String EXTRA_FROM =
      "com.isunland.managesystem.ui.SearchPersonListFragment.EXTRA_FORM";
  public static final String VALUE_COMMON =
      "com.isunland.managesystem.ui.SearchPersonListFragment.COMMON";
  public static final String VALUE_TASK_COLLECT =
      "com.isunland.managesystem.ui.SearchPersonListFragment.VALUE_TASK_COLLECT";
  public static final String VALUE_APPOINTER =
      " com.isunland.managesystem.ui.SearchPersonListFragment.VALUE_APPOINTER";
  private SearchPersonAdapter mAdapter;
  private ArrayList<SummaryStaff> mList;

  private EditText mSearchEt;
  private String mFrom;

  public static Fragment newInstance(String from) {
    Bundle bundle = new Bundle();
    bundle.putString(EXTRA_FROM, from);

    SearchPersonListFragment fragment = new SearchPersonListFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitleCustom(R.string.selectPerson);
    mFrom = getArguments().getString(EXTRA_FROM);
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    mListview.setDivider(null);
    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.header_search_person, null, false);
    mSearchEt = (EditText) header.findViewById(R.id.et_search_searchPersonHeader);
    mSearchEt.addTextChangedListener(new TextWatcher() {

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (mList == null || mList.size() == 0) {
          return;
        }
        String query = s.toString().trim();
        if (query.equals("")) {
          setAdapter(mList);
        } else {
          updateItems(query);
        }
        mSearchEt.requestFocus();
      }

      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // Auto-generated method stub

      }

      @Override public void afterTextChanged(Editable s) {
        // Auto-generated method stub

      }
    });
    TextView mDepartmentTv = (TextView) header.findViewById(R.id.tv_department_searchPersonHeader);
    mDepartmentTv.setText(CurrentUser.newInstance(getActivity()).getDeptName());
    mListview.addHeaderView(header);
  }

  @Override public String getUrl() {
    if (mFrom != null && mFrom.equals(VALUE_TASK_COLLECT)) {
      return ApiConst.URL_GET_MANAGE_STAFF;
    } else if (mFrom != null && mFrom.equals(VALUE_COMMON)) {
      //所有人员
      return ApiConst.URL_QUERY_MEMBER;
    } else {

      return ApiConst.URL_GETATTENDANCE_STAFF;
    }
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    if (mFrom != null && mFrom.equals(VALUE_TASK_COLLECT)) {
      params.put("jobno", CurrentUser.newInstance(getActivity()).getJobNumber());
      params.put("ifContainDept", "false");
      params.put("ifContainStaff", "true");
      params.put("memCode", CurrentUser.newInstance(getActivity()).getMemberCode());
      return params;
    } else if (mFrom != null && mFrom.equals(VALUE_COMMON)) {
      params.put("type", "user");
      String memberCode = CurrentUser.newInstance(getActivity()).getMemberCode();
      params.put("orgCode", memberCode);
      return params;
    } else {

      return super.getparameters();
    }
  }

  @Override public void resolveResponse(String json) {
    ArrayList<AttendanceSummaryStaffDialog.SummaryStaff> rows;
    if (mFrom != null && mFrom.equals(VALUE_COMMON)) {
      Type listType = new TypeToken<ArrayList<MessageContact>>() {
      }.getType();

      ArrayList<MessageContact> messageDialogs = new Gson().fromJson(json, listType);
      rows = new AttendanceSummaryStaffDialog().turn(messageDialogs);
    } else {

      AttendanceSummaryStaffDialog original =
          new Gson().fromJson(json, AttendanceSummaryStaffDialog.class);
      rows = original.getDataList();
    }

    if (rows == null || rows.size() == 0) {
      ToastUtil.show(R.string.that_is_all);
      return;
    }

    mList = rows;
    setAdapter(rows);
  }

  private void setAdapter(List<SummaryStaff> detail) {

    if (mList == null) {
      mList = new ArrayList<>();
    }
    mAdapter = new SearchPersonAdapter(getActivity(), detail);
    setListAdapter(mAdapter);
    ((SearchPersonAdapter) getListAdapter()).notifyDataSetChanged();
  }

  public void updateItems(String query) {

    // 直接通过中文人名来进行搜索
    ArrayList<SummaryStaff> listNames = new ArrayList<>();// 获取人名
    String str;
    String deptStr;
    for (int i = 0; i < mList.size(); i++) {
      str = mList.get(i).getName();
      deptStr = mList.get(i).getDeptName();
      if (str.contains(query) || deptStr.contains(query)) {
        listNames.add(mList.get(i));
      }
    }

    setAdapter(listNames);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // 响应返回图标
      case android.R.id.home:

        getActivity().finish();
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {

    SummaryStaff item = mAdapter.getItem(position - 2);
    if (item == null) return;
    CustomerDialog dialog =
        new CustomerDialog(item.getName(), item.getId(), item.getJobNo(), item.getDeptCode(),
            item.getDeptName());

    Intent i = new Intent();
    i.putExtra(EXTRA_VALUE, dialog);
    LogUtil.i("name===" + dialog.getName() + ",id==" + dialog.getId());
    getActivity().setResult(Activity.RESULT_OK, i);
    getActivity().finish();
  }

  @Override public boolean isNeedRoleType() {
    //在委派人获取人员的时候不要传roletypeFlag
    return !(mFrom != null && mFrom.equals(VALUE_APPOINTER)) && super.isNeedRoleType();
  }
}
